package com.android.fragmentdemo.thread6

import org.junit.Test
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue

class Demo6 {
    @Test
    fun testThreadPool() {
        val threadPool = DefineThreadPool(6)
        threadPool.submit {
            println("this is a ThreadPool")
        }

        Thread.sleep(10 * 1000)
    }

    class DefineThreadPool(coreSize:Int) {

        private val workers = mutableListOf<Worker>()
        private val blockingQueue = LinkedBlockingQueue<Runnable>()

        init {
            for (i in 0.until(coreSize)) {
                val worker = Worker(blockingQueue)
                worker.start()
                workers.add(worker)
            }
        }

        fun submit(runnable: Runnable) {
            try {
                blockingQueue.put(runnable)
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            }
        }
    }

    class Worker(blockingQueue: BlockingQueue<Runnable>) : Thread() {

        private val mBlockingQueue = blockingQueue

        override fun run() {
            super.run()
            while (true) {
                try {
                    val runnable = mBlockingQueue.take()
                    runnable.run()
                } catch (ex: InterruptedException) {
                    ex.printStackTrace()
                }
            }
        }
    }

}